package com.example.demo.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.JsonArray;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;

import com.example.demo.commom.ressponse.JsonResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("v1/douqi")
public class BaiduTranslateAPI {
    // 请替换为你的APP ID和密钥
    private static final String APP_ID = "20240423002032540";
    private static final String SECRET_KEY = "ssniLTStVKapZmlnx3Bd";

    @PostMapping("fangyi")
    public JsonResult fangyi(@PathVariable long id){
        String query = "万众一心"; // 要翻译的文本
        String from = "zh"; // 原文语言
        Scanner sc = new Scanner(System.in);
        System.out.println("输出编码");
        String st = sc.next();
        int num = 0;
        //001中文,002缅甸语,003泰语,004越南语,005印度尼西亚语,006马来语,007老挝语,008菲律宾语,009英语
        String[] arr = {"001", "002", "003", "004", "005", "006", "007", "008", "009"};
        for (int i = 0; i < arr.length; i++) {
            if (st.equals(arr[i])) {
                num = i;
            }
        }
        //中文（zh）、缅甸语（my）、泰语（th）、越南语（vi）、印度尼西亚语（id）、马来语（ms）、老挝语（lo）、菲律宾语（fil）和英语（en）
        String[] toLanguages = {"zh", "my", "th", "vi", "id", "ms", "lo", "fil", "en"};
        String to = toLanguages[num];

        String result = null; // 调用翻译API接口
        try {
            result = translate(query, from, to);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.ok(parseResult(result));
    }

    public static String translate(String query, String from, String to) throws Exception {
        String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        Map<String, String> params = new HashMap<>();
        params.put("q", URLEncoder.encode(query, "UTF-8"));
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APP_ID);
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        String sign = MD5Uti.md5(APP_ID + query + salt + SECRET_KEY);
        params.put("sign", sign);

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);

        URL realUrl = new URL(url + "?" + sb.toString());
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder result = new StringBuilder();
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        in.close();
        connection.disconnect();

        return result.toString();
    }

    public static String parseResult(String jsonResult) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonResult, JsonObject.class);

        // 检查是否存在 "trans_result" 字段
        if (jsonObject.has("trans_result")) {
            JsonArray transResultArray = jsonObject.getAsJsonArray("trans_result");

            // 检查翻译结果数组是否为空
            if (transResultArray.size() > 0) {
                JsonObject translationObj = transResultArray.get(0).getAsJsonObject();

                // 检查是否存在 "dst" 字段
                if (translationObj.has("dst")) {
                    String translatedText = translationObj.get("dst").getAsString();
                    return translatedText;
                }
            }
        }
        return "翻译失败"; // 如果无法解析翻译结果，返回一个默认值或错误提示
    }
}
